package cn.tyf.service;

import cn.tyf.common.ConstAutoConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Service
public class CodeService {

    @Autowired
    private ConstAutoConfig constAutoConfig;
    public BufferedImage Code(HttpServletRequest request){
        Integer width = 100;
        Integer height = 37;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0,0,width,height);

        //产生4个随机验证码，12Ey
        String checkCode = getCheckCode();

        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体",Font.BOLD,24));
        //向图片上写入验证码
        g.drawString(checkCode,15,25);

        Random random = new Random();
        for (int i = 1; i < 10 ; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }
        request.getSession().setAttribute(constAutoConfig.getCODE(),checkCode);
        return image;

    }
    /**
     * 产生4位随机字符串
     */
    public String getCheckCode() {
        String base = constAutoConfig.getBASE();
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i=1;i<=5;i++){
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        ConstAutoConfig constAutoConfig = new ConstAutoConfig();
        System.out.println(constAutoConfig.getApiKey());
    }
}
